/**
 * ========================================
 * 月份选择器
 * @author johnnyzheng(johnnyzheng@tencent.com)
 * @version 2012-08-24 init
 * 		13-03-05
		1、月份选择扩展接口，使当年的未来月份也可选。
		14-01-05
		修复月份选择器的bug
		1、IE9，IE10下，只能选一个月
		2、跨年选择的时候，月份是反的
		3、跨年的选中态有问题
		14-05-29
		默认选中月份bug修复
		返回的对象格式支持年份/月份
		支持默认选中上个月的参数
 *
 * ========================================
 */

function MonthPicker() {
    getCurrentDate= function() {
            var current = new Date();
            return {
                'year': current.getFullYear(),
                'month': current.getMonth() + 1
            };
    };
   this._conf= {
        //月份选择器的开始年
        startYear: 1970,
        //默认是今年
        endYear: new Date().getFullYear(),
        //月份选择器的选择面板的月份排布的列数
        cols: 4,
        //月份选择器的选择面板的月份排布的行数
        rows: 3,
        //容器ID
        container: 'gri_monthPicker_wrapper',
        //选择框的id
        calendar: 'gri_monthPicker_panel',
        //日期框体 id
        dataTable: 'gri_monthPicker_table',
        // 日期表格的CSS类
        containerCss: 'calendar cf',
        // 时间选择的样式
        selectCss: 'current',
        //内容样式
        contentCss: 'calendar_cont cf',
        //表格样式
        tableCss: 'calendar-month',
        //不可选样式
        disabledCss: 'dis',
        min: {year:1970,month:1},
        max: getCurrentDate(),
        //输入控件
        input: {},
        //ID
        id: 'month_picker',
        //trigger 额外触发器
        trigger: 'month_trigger',
        //回调函数
        callback: function(obj) {
            return true
        },
        //是否加载即回调
        autoCommit: false,
        //返回的是月份，还是日期，默认是月份
        returnDate: false,
        //默认选中的时间月份 , 字符串规范形如： '201302'
        defaultMonth: '',
        //默认选中上个月
        lastMonth: false,
        //支持区间选择
        period: false,
        //开始月份，只有上述为true时才生效
        start_month: '',
        //结束月份，只有上述为true时才生效
        end_month: '',
        //所有月份都可选
        all_month_valid: false,
        //默认文字
        defaultText: ' 至 '
    };
  
    //最终的返回值，初始值是当前年月
    this.assemble= getCurrentDate();

    /**
     * @description 外部调用接口
     * @param {String} id, element id
     * @param {Object} 外源配置
     */
    this.create=function(id, conf) {
        var that = this;
        that._conf.id = id;
        that._conf = $.extend(true, that._conf, conf);
        $(id).each( function() {
            $(this).bind('click', function() {
                that.show(this);
                return false;
            });
        });
       $(document).on('click', function(evt) {
            $("#"+that._conf.container).hide();
        });
    },
    //展示框体
    this.show= function(ref) {
        this._conf.input = ref;
        if(ref.value!=""&&ref.value.indexOf("-")){
            this.assemble = {    'year': parseInt(ref.value.split('-')[0]),
                'month': parseInt(ref.value.split('-')[1])}
        }else{
            this.assemble = getCurrentDate();
        }
        //如果已经存在div，则不重复创建
        var container =  $("#"+this._conf.container);
        if (container.attr("id")) {
            var pos = $(ref).offset();
            var offsetHeight = $(ref).attr('offsetHeight');
            container.css("display", 'block');
            container.css("top", pos.top + (offsetHeight ? offsetHeight - 1 : 32) + 'px');
            container.css("left", pos.left + 'px');
          
        }else{
          this.createPanel(ref);
        }
        this.bind(ref);
    },
    //初始化
    this.createPanel= function(ref) {
                //创建面板
        var $div = $('<div>', {id:this._conf.container});
        $div.addClass(this._conf.containerCss);
        $div.css("zIndex",9999);
        //调整位置
        var pos = $(ref).offset();
        var offsetHeight = $(ref).attr('offsetHeight');
        $div.css("top", pos.top + (offsetHeight ? offsetHeight - 1 : 32) + 'px');
        $div.css("left",pos.left + 'px');
     
        var $contentDiv = $('<div>',{"id":this._conf.calendar});
        $contentDiv.addClass(this._conf.contentCss);
        $contentDiv.id = this._conf.calendar;
        $contentDiv.append($('<i class="i_pre" style="z-index:1" id="gri_preYear"></i>'));
        $contentDiv.append($('<i class="i_next" style="z-index:1" id="gri_nextYear"></i>'));
        $div.append($contentDiv);
        $div.css("display","block");
        $(document.body).append($div);

      
        //点击输入框的时候，初始化的月份选择器的面板
        var $table = $('<table>');
        $table.addClass(this._conf.tableCss);
        var $cap =$('<caption>');
        var $sp =$('<span>',{"id":'gri_year'});
      
        $sp.append(this._conf.endYear + '年');
        $cap.append($sp);
        $table.append($cap);

        var $tbody = $('<tbody>',{"id": this._conf.dataTable});
        var $tr = $('<tr>');
        var $td = $('<td>');
        $table.append($tbody);
        this._conf.calendar ? $("#"+this._conf.calendar).append($table) : $(document.body).append($table);

        //构造月份等面板
        this.constructMonth(ref);
      

        $('#gri_preYear').click(function() {
            that.preYear();
        });
        $('#gri_nextYear').click(function() {
            that.nextYear();
        });
        return $table;

    },
    this.validate=function(){
        if((this.assemble.year< this._conf.min.year) || (this.assemble.year>this._conf.max.year)){
            return false;
        }
        if((this._conf.max.year=this.assemble.year) && (this.assemble.month>this._conf.max.month)){
            return false;
        }
        return true;
    }
    this.bind=function(ref ){
            var that = this;
            var cells = $('#gri_monthPicker_table').find('td');
             $(cells).off("click");
             $(cells).on("click",function(){
                        var month = (/^gri_month(\d+)/).test(this.getAttribute('id')) && (/^gri_month(\d+)/).exec(this.getAttribute('id'))[1];
                        that.assemble.month = month;
                        if(that.validate()){
                            ref.value = [that.assemble.year,  that.assemble.month].join('-') ;
                            $("#"+that._conf.container).hide(); 
                        }
                                        
            });
         
    }
    //构造月份
    this.constructMonth=function(ref) {
        that = this;
        $('#' + this._conf.dataTable).html('');
        //months 容器，预留后面扩展的参数接口
        var months = {
            data: {
                1: [1, 2, 3, 4],
                2: [5, 6, 7, 8],
                3: [9, 10, 11, 12]
            },
            typical: {
                1: '一',
                2: '二',
                3: '三',
                4: '四',
                5: '五',
                6: '六',
                7: '七',
                8: '八',
                9: '九',
                10: '十',
                11: '十一',
                12: '十二'
            },
            special: {}
        };
        //遍历月份接口
        for (var p in months.data) {
            var $tr = $("<tr>")
            for (var i = 0; i < months.data[p].length; i++) {
                var $td = $('<td>',{"id":'gri_month' + months.data[p][i]});
                $td.html(months.typical[months.data[p][i]] + '月');
                $tr.append($td);
            }
            $('#' + this._conf.dataTable).append($tr);
        }

    },
    //上一年
    this.preYear= function() {
        if(this.asseble.year>this._conf.min.year){
            --this.assemble.year;
            $('#gri_year').html(this.assemble.year + '年');

        }
    },
    //下一年
    this.nextYear= function() {
        if(this.assemble.year<this._conf.max.year){
              ++this.assemble.year;
            $('#gri_year').html(this.assemble.year + '年') ;
        }
    }
  
   
   

  
 
};


	